#include "./steam_task.h"
#include "../heat_driver/ctrl.h"
#include "../heat_driver/sensor.h"

namespace heat_task {

SteamTask steamTask;

using namespace heat_driver;

void SteamTask::init_start() {
    m_mq.init();
    start();
}

void SteamTask::run() {

    for (;;) {
        switch (m_mv.mode) {
            case Mode::BEGIN: do_begin(); break;
            case Mode::CLOSE: do_close(); break;
            case Mode::OPEN: do_open(); break;
        }
    }
}

constexpr uint32_t MAX_TEMP = 200;
constexpr uint32_t BEGIN_TIMEOUT = 2 * 60 * 1000;

void SteamTask::do_begin() {
    uint32_t time_count = 0;
    ctrl.open(Ctrl::Parts::V2);

    for (;;) {

        if (sensor.steam_temp() >= MAX_TEMP) {
            ctrl.close(Ctrl::Parts::STEAM_HEAT);
        } else {
            ctrl.open(Ctrl::Parts::STEAM_HEAT);
        }

        if (wait(1000)) {
            break;
        }

        time_count += 1000;
        if (time_count >= BEGIN_TIMEOUT) {
            m_mv.mode = Mode::CLOSE;
            break;    
        }
    }
    ctrl.close(Ctrl::Parts::V2);
    ctrl.close(Ctrl::Parts::STEAM_HEAT);
}

void SteamTask::do_open() {
    ctrl.open(Ctrl::Parts::STEAM_HEAT);
    ctrl.open(Ctrl::Parts::V2);
    
    ctrl.open(Ctrl::Parts::STEAM_PUMP);
    ctrl.close(Ctrl::Parts::V2);
    ctrl.open(Ctrl::Parts::V6);
    ctrl.open(Ctrl::Parts::V1);
    if (!wait( m_mv.sec * 1000 )) {
        m_mv.mode = Mode::CLOSE;
    }
    ctrl.close(Ctrl::Parts::STEAM_PUMP);
    ctrl.close(Ctrl::Parts::V6);
    ctrl.close(Ctrl::Parts::V1);
    ctrl.close(Ctrl::Parts::STEAM_HEAT);
}

void SteamTask::do_close() {
    ctrl.open(Ctrl::Parts::V2);
    bool ret = wait(60 * 1000);
    ctrl.close(Ctrl::Parts::V2);
    if (ret) {
        return;
    }
    wait();
}


}
